package io.zhengsh.nio;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class FileChannelDemo2 {

	// FileChannel 读取数据到 buffer 中
	public static void main(String[] args) throws IOException {
		// 创建 FileChannel
		RandomAccessFile accessFile = new RandomAccessFile("C:\\a.txt", "rw");
		FileChannel fileChannel = accessFile.getChannel();

		String newData = "new string to write to file ..." + System.currentTimeMillis();
		// 创建 buffer
		ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
		byteBuffer.clear();
		byteBuffer.put(newData.getBytes());

		byteBuffer.flip();

		while (byteBuffer.hasRemaining()) {
			fileChannel.write(byteBuffer);
		}
		fileChannel.close();
		System.out.println("end");
	}
}